<?php

namespace App\Recharge\Api;

use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;

class Chongqinghaixin extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $data = [
            'customer_id'       => $bean->getSupplierNum(),
            'timestamp'         => time(),
            'product_id'        => $bean->getGoodsId(),
            'recharge_account'  => $bean->getAccount(),
            'quantity'          => $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量
            'notify_url'        => $bean->getNotifyUrl(),
            'outer_order_id'    => $bean->getOrderNo(),//订单号
            'safe_cost'         => $bean->getUnitPrice(),
            'client_ip'         => $bean->getIp(),
        ];
        ksort($data);
        $signStr = $bean->getSecretKey();
        foreach ($data as $k => $v) {
            $signStr .= $k . $v;
        }
        $data['sign'] = strtolower(md5($signStr));

        return $data;
    }

    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        return $this->httpClient($http)->asJson()->withHeader('Authorization-User', $bean->getSupplierNum())->post($config->recharge_url, $this->rechargeData($bean));
    }

    /**
     * @inheritDoc
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('state', '');
        $order_sn = $request->input('outer_order_id', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, [200, 500]))->setRechargeSuccess($status == 200);

    }
}
